import Taro, {Component} from '@tarojs/taro'
import {View, Picker, Input} from '@tarojs/components'
import {AtMessage, AtRate, AtButton} from 'taro-ui'
import qs from 'qs'
import { connect } from '@tarojs/redux'
import './index.scss'
import {getTopicInfo, getSoreTopicScore, saveRaterTopicInfo} from '../service'
import {setRefresh} from "../../../actions/refresh";

@connect(({ refresh }) => ({
  refresh
}), (dispatch) => ({
  setRefresh (isRefresh) {
    dispatch(setRefresh(isRefresh))
  },
}))
export default class score extends Component {

  config = {
    navigationBarTitleText: '评分'
  };

  constructor(props) {
    super(props);
    this.state = {
      isDetail: true,
      formData: {
        scoreTopicScoreDtoArrayList: []
      },
      problemList: [],
      scoreData:{}
    }
  }

  componentDidMount() {
    let array = window.location.hash.split('?');
    let obj = qs.parse(array[1]);
    let scoreData = JSON.parse(obj.scoreData);

    getTopicInfo(scoreData.programId).then(problemList => {
      if (scoreData.isDetail) {
        getSoreTopicScore(scoreData.id).then(scoreRes => {
          this.setState({
            problemList: problemList,
            formData: {id: scoreData.id, scoreTopicScoreDtoArrayList: scoreRes},
            isDetail: scoreData.isDetail,
            scoreData
          });
        })
      } else {
        this.setState({
          problemList: problemList,
          formData: {id: scoreData.id, scoreTopicScoreDtoArrayList: []},
          isDetail: scoreData.isDetail,
          scoreData
        });
      }
    })
  }

  onSubmit = () => {
    let {formData, problemList} = this.state;
    if (formData.scoreTopicScoreDtoArrayList.length === 0 && problemList.length !== formData.scoreTopicScoreDtoArrayList){
      Taro.atMessage({message: '存在未评分项，请进行评分后提交！', type: 'error'});
      return;
    }
    saveRaterTopicInfo(formData).then(res => {
      if (res.flag){
        Taro.atMessage({message: '评分成功！', type: 'success'});
        this.props.setRefresh(true);
        setTimeout(()=>{
          Taro.navigateBack()
        },300)
      }
    });
  };

  handleChange = (value, item) => {
    const {formData} = this.state;
    let dataItem = {id: item.id, maxScore: item.maxScore, score: value, title: item.title};
    let obj = {...formData};
    let sameItem = obj.scoreTopicScoreDtoArrayList.find(oldItem => oldItem.id === item.id);
    if (sameItem){
      sameItem.score = value;
    }else {
      obj.scoreTopicScoreDtoArrayList.push(dataItem);
    }
    this.setState({formData: obj})
  };

  handleBack = (value, item) => {
    this.props.setRefresh(true);
    Taro.navigateBack()
  };


  render() {
    let {formData, problemList, isDetail, scoreData} = this.state;
    return (
      <View className='score-360-details'>
        <AtMessage/>
        <View className='topBar'>
          <AtButton size='small' onClick={this.handleBack}>返回</AtButton>
          {
            problemList.length > 0 ? <View>对{scoreData.name}的评分：{problemList.reduce((totle,item,)=>{
              let hasItem = formData.scoreTopicScoreDtoArrayList.find(scoreItem => scoreItem.id===item.id);
              let score =  hasItem ? hasItem.score : 0
              return totle + score
            },0)}</View> : <View/>
          }
        </View>
        <View className='problem-body'>
          {
            problemList.length > 0 &&
            problemList.map((item, index) =>{
                let hasItem = formData.scoreTopicScoreDtoArrayList.find(scoreItem => scoreItem.id===item.id);
                return <View className='problemItem' key={index}>
                  <View className='title'>{`${index+1}. ${item.title}`}</View>
                  <View className='rate'>
                    <View>
                      {
                        isDetail ?
                          <AtRate max={item.maxScore} size={25} value={hasItem ? hasItem.score : 0}/> :
                          <AtRate max={item.maxScore} size={25} value={hasItem ? hasItem.score : 0}
                                  onChange={(value) => this.handleChange(value, item)}/>
                      }
                    </View>
                    <View>{hasItem ? hasItem.score : 0}分</View>
                  </View>
                </View>
              }
            )
          }
        </View>

        {
          !isDetail &&
          <View className='btn-view'>
            <AtButton type='primary' onClick={this.onSubmit.bind(this)}>提交</AtButton>
          </View>
        }
      </View>
    )
  }
}
